import { useState } from "react";
import { ethers } from "ethers";
import ErrorNotification from "./ErrorNotification";


function Bet({ toggleBet, issue , market, provider }) {
  const [selectedOption, setSelectedOption] = useState(null);
  const [betAmount, setBetAmount] = useState("");
  const [error, setError] = useState(null);

  const handleOptionClick = (index) => {
    setSelectedOption(index);
  };

  const handleBet = async () => {
    if(issue.isResolved) {
      setError("Issue is already resolved")
      return
    }
    const amount = ethers.parseUnits(betAmount,18)
    const signer = await provider.getSigner()
    const transaction =  await market.connect(signer).placeBet(issue.id, selectedOption, amount ,{ value: amount });
    transaction.wait()
    toggleBet()
  };

  const handleClaim = async () =>{
    //check if issue is resolved
    if(!issue.isResolved) {
      setError("Issue is not resolved yet")
      return
    }
    const signer = await provider.getSigner()
    //check winningbet
    const issueId = issue.id
    const address = await signer.getAddress()
    const winningOption = issue.winningOption
    const amount = await market.connect(signer).getBet(issueId,winningOption)
    if(amount == 0) {
      setError("You have no winning bet")
      return
    }
    //claim reward
    const transaction = await market.connect(signer).claim(issue.id)
    transaction.wait()
    toggleBet()
  }

  return (
    <div className="bg-gray-900 border-4 border-pink-500 p-6 max-w-lg mx-auto shadow-[8px_8px_0_#ff00ff]">
      {error && <ErrorNotification message={error} onClose={() => setError(null)} />}
      <h1 className="text-pink-400 text-3xl font-pixel mb-4">Bet on</h1>
      <h2 className="text-white text-2xl font-pixel mb-4">{issue.description}</h2>

      <div className="space-y-3">
        {issue.options.map((option, index) => (
          <p
            key={index}
            onClick={() => handleOptionClick(index)}
            className={`p-3 border-4 border-pink-400 bg-gray-800 text-white shadow-[4px_4px_0_#ff00ff] cursor-pointer font-pixel ${
              selectedOption === index ? "bg-pink-500 border-black" : "hover:bg-pink-700"
            }`}
          >
            {option}
          </p>
        ))}
      </div>

      <div className="mt-6 flex items-center border-4 border-pink-400 bg-gray-800 shadow-[4px_4px_0_#ff00ff]">
        <input
          type="number"
          placeholder="Enter your bet"
          value={betAmount}
          onChange={(e) => setBetAmount(e.target.value)}
          className="w-full p-3 bg-transparent text-white font-pixel placeholder-pink-300 focus:outline-none"
        />
        <span className="text-pink-300 text-xl font-pixel px-3">ETH</span>
      </div>

      <div className="mt-6 flex flex-col space-y-4">
        <button
          className={`w-full p-3 border-4 border-black text-black bg-green-500 shadow-[4px_4px_0_#00ff00] font-pixel ${
            selectedOption === null || !betAmount ? "opacity-50 cursor-not-allowed" : "hover:bg-green-600"
          }`}
          onClick={handleBet}
          disabled={selectedOption === null || !betAmount}
        >
          Bet
        </button>

        <button 
          onClick={handleClaim}
          className="w-full p-3 border-4 border-black text-black bg-yellow-500 shadow-[4px_4px_0_#ffff00] hover:bg-yellow-600 font-pixel">
          Claim
        </button>

        <button
          onClick={toggleBet}
          className="w-full p-3 border-4 border-black text-black bg-red-500 shadow-[4px_4px_0_#ff0000] hover:bg-red-600 font-pixel"
        >
          Close
        </button>
      </div>
    </div>
  );
}

export default Bet;
